# Python 2.6.4
# Project Euler, Problem 92
# Copyright 2010 Talha Zaman

def chain(n): return sum([int(c)**2 for c in str(n)])
seq = [0]
for i in range(1,10000000):
    c = chain(i)
    while c != 1 and c != 89 and c>len(seq): c = chain(c)
    if c<len(seq): seq.append(seq[c])
    elif c == 1: seq.append(0)
    else: seq.append(1)
print sum(seq)
